<template>
  <el-card shadow="always">
    <!---- -- -- -- 头部-- -- -- -- -- -- -->
    <div slot="header">
      <!-- 路径导航 -->
      <Breadcrumb/>
    </div>
    <!---- -- -- -- 内容区域-- -- -- -- -- -- -->
    <el-alert show-icon
              title="注意：只允许为第三级分类设置相关参数"
              type="warning">
    </el-alert>
    <br>
    <div>
      <span>请选择商品分类：</span>
      <el-cascader v-model="chooseCateId"
                   :options="allCateList"
                   @change="getParamsList"
                   :props="{label:'cat_name',value:'cat_id'}"></el-cascader>
    </div>
    <br>
    <!-- tab组件 -->
    <el-tabs v-model="activeName"
             @tab-click="getParamsList">
      <el-tab-pane label="动态参数"
                   name="many">
        <el-button :disabled="isBtnDisabled"
                   type="primary"
                   @click="isShow=true">添加动态参数</el-button>
        <br> <br>
        <!-- 动态参数表格 -->
        <el-table :data="manyList"
                  border>
          <el-table-column type="expand"
                           width="130px">
            <template slot-scope="scope">
              <!-- 标签列表 -->
              <el-tag class="mr10"
                      :key="tag"
                      v-for="(tag,idx) in scope.row.attr_vals"
                      closable
                      @close="delTags(scope.row,idx)"
                      :disable-transitions="false">
                {{tag}}
              </el-tag>
              <!-- 输入框 -->
              <el-input style="width:140px;"
                        ref="addTagInput"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        v-if="scope.row.inputShow"
                        v-model="scope.row.inputValue"></el-input>
              <!-- 增加按钮 -->
              <el-button v-else
                         @click="showInput(scope.row)"
                         type="primary"
                         class="button-new-tag"
                         size="small"
                         icon="el-icon-plus">增加</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index"
                           width="130px"
                           label="序号"></el-table-column>
          <el-table-column prop="attr_name"
                           label="参数名"></el-table-column>
          <el-table-column label="操作"
                           width="200px">
            <template slot-scope="scope">
              <el-button circle
                         type="success"
                         @click="editHandler(scope.row)"
                         size="small"
                         icon="el-icon-edit"></el-button>
              <el-button circle
                         type="danger"
                         size="small"
                         @click="delHandler(scope.row)"
                         icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性"
                   name="only">
        <el-button :disabled="isBtnDisabled"
                   type="primary"
                   @click="isShow=true">添加静态属性</el-button>
        <br> <br>
        <!--静态属性表格 -->
        <el-table :data="onlyList"
                  border>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <!-- 标签列表 -->
              <el-tag class="mr10"
                      :key="tag"
                      v-for="(tag,idx) in scope.row.attr_vals"
                      closable
                      @close="delTags(scope.row,idx)"
                      :disable-transitions="false">
                {{tag}}
              </el-tag>
              <!-- 输入框 -->
              <el-input style="width:140px;"
                        ref="addTagInput"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        v-if="scope.row.inputShow"
                        v-model="scope.row.inputValue"></el-input>
              <!-- 增加按钮 -->
              <el-button v-else
                         @click="showInput(scope.row)"
                         type="primary"
                         class="button-new-tag"
                         size="small"
                         icon="el-icon-plus">增加</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index"
                           label="序号"></el-table-column>
          <el-table-column prop="attr_name"
                           label="参数名"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button circle
                         type="success"
                         @click="editHandler(scope.row)"
                         size="small"
                         icon="el-icon-edit"></el-button>
              <el-button circle
                         type="danger"
                         size="small"
                         @click="delHandler(scope.row)"
                         icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!-- 弹框 -->
    <el-dialog :title="activeName==='many' ? this.isAdd ?  '添加动态属性': '修改动态属性'   : this.isAdd ?'添加静态属性':'修改静态属性'  "
               :visible.sync="isShow"
               width="30%">
      <el-form :model="formData"
               ref="form"
               label-width="100px"
               :inline="false"
               size="normal">
        <el-form-item label="属性名"
                      required>
          <el-input v-model="formData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="isShow = false">Cancel</el-button>
        <el-button type="primary"
                   @click="AttrSubmit">OK</el-button>
      </span>
    </el-dialog>

  </el-card>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      chooseCateId: [], // 级联选择器绑定变量
      allCateList: [], // 所有商品分类
      activeName: 'many', // 注意我们把值写成 many或only 目的是能够便捷的知道当前属于哪个类型操作
      onlyList: [], // 静态属性列表
      manyList: [], // 动态参数列表
      isShow: false, // 弹框是否显示
      isAdd: true, // 是否为添加行为
      formData: { // 表格数据
        attr_name: ''
      }
    }
  },
  computed: {
    // 按钮是否禁用
    isBtnDisabled () {
      return this.chooseCateId.length !== 3
    },
    // 分类ID
    cateId () {
      return this.chooseCateId.length === 3 ? this.chooseCateId[2] : ''
    }
  },
  created () {
    this.getAllCateList()
  },
  methods: {
    // 获取所有分类
    async getAllCateList () {
      const { data: res } = await this.$axios.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.allCateList = res.data
    },
    // 获取分类参数列表
    async getParamsList () {
      // 拦截判断（tab切换的时候没有选择分类）
      if (!this.cateId) return
      // 发送请求、错误处理、成功处理
      const { data: res } = await this.$axios.get('/categories/' + this.cateId + '/attributes?sel=' + this.activeName)
      if (res.meta.status !== 200) return res.meta.msg
      // 加工数据！ 把 attr_vals 变成一个数组；增加一个inputValue字段存储输入框的数据；增加inputShow 控制条件显示
      res.data.forEach(val => {
        if (val.attr_vals) {
          val.attr_vals = val.attr_vals.split(',')
        } else {
          val.attr_vals = []
        }
        val.inputValue = ''
        val.inputShow = false
      })

      this[this.activeName + 'List'] = res.data
    },
    // 添加动态或者静态属性名
    async AttrSubmit () {
      if (!this.formData.attr_name) return this.$message.warning('请输入属性名')
      if (this.isAdd) { // 添加行为
        const { data: res } = await this.$axios.post(`/categories/${this.cateId}/attributes`, {
          attr_sel: this.activeName,
          attr_name: this.formData.attr_name
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
      } else { // 修改行为
        const { data: res } = await this.$axios.put(`/categories/${this.cateId}/attributes/${this.formData.attr_id}`, {
          attr_sel: this.activeName,
          attr_name: this.formData.attr_name
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        delete this.formData.attr_id // 删除对象某个属性
        this.isAdd = true // 变回添加行为
      }
      this.formData.attr_name = ''
      this.isShow = false
      this.getParamsList()
    },
    // 修改事件
    editHandler (row) {
      // 回显数据
      this.formData.attr_name = row.attr_name
      this.formData.attr_id = row.attr_id
      // 修改行为
      this.isAdd = false
      // 打开弹框
      this.isShow = true
    },
    // 显示输入框
    showInput (row) {
      // 显示输入框
      row.inputShow = true // 条件渲染就要去编译了，但是渲染是需要耗时的！
      // 找到输入框，让其获取焦点
      // this.$nextTick( ()=>{ 等到渲染完成之后再做某件事情！ } )
      this.$nextTick(() => {
        this.$refs.addTagInput.$refs.input.focus()
      })
    },
    // 输入框数据提交事件（失焦和enter确定）
    async handleInputConfirm (row) {
      // 没值就关闭，跳出
      if (!row.inputValue) {
        row.inputShow = false
        return false
      }
      // 有值就去提交
      // 取出这一行的属性值
      const attrVals = [...row.attr_vals]
      attrVals.push(row.inputValue)
      const { data: res } = await this.$axios.put(`/categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_sel: row.attr_sel,
        attr_name: row.attr_name,
        attr_vals: attrVals.join(',')
      })
      if (res.meta.status !== 200) {
        row.inputValue = ''
        row.inputShow = false
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      row.attr_vals.push(row.inputValue) // 成了要push一次！更新视图
      row.inputValue = ''
      row.inputShow = false
    },
    // 标签删除事件
    async delTags (row, idx) {
      try {
        // 确认框
        await this.$confirm('确定删除吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 删除一个数据
        const attrVals = [...row.attr_vals]
        attrVals.splice(idx, 1)
        // 发送请求
        const { data: res } = await this.$axios.put(`/categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_sel: row.attr_sel,
          attr_name: row.attr_name,
          attr_vals: attrVals.join(',')
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        row.attr_vals.splice(idx, 1) // 成了要push一次！更新视图
      } catch (error) {
        console.log(error)
      }
    },
    // 删除属性事件
    async delHandler (row) {
      try {
        // 确认框
        await this.$confirm('确定删除吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 发送请求
        const { data: res } = await this.$axios.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsList()
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped>
.mr10{
  margin-right: 10px;
}
</style>
